<template>
  <div class="user-profile-container">
    <!-- 头部信息 -->
    <div class="profile-header">
      <div class="avatar-container">
        <img
          :src="user.avatarUrl || 'https://via.placeholder.com/80'"
          alt="用户头像"
          class="avatar"
        />
        <input
          type="file"
          ref="avatarInput"
          @change="handleAvatarChange"
          accept="image/*"
          style="display: none"
        />
        <button class="edit-avatar-btn" @click="$refs.avatarInput.click()">
          更换头像
        </button>
      </div>
      <h2 class="username">{{ user.nickname || user.username }}</h2>
      <button class="logout-btn" @click="handleLogout">退出登录</button>
    </div>

    <!-- 个人信息展示 -->
    <div class="profile-info">
      <div class="info-item">
        <span class="info-label">用户名：</span>
        <span class="info-value">{{ user.username }}</span>
      </div>
      <div class="info-item">
        <span class="info-label">昵称：</span>
        <span class="info-value">{{ user.nickname }}</span>
      </div>
      <div class="info-item">
        <span class="info-label">手机号：</span>
        <span class="info-value">{{ user.phone }}</span>
      </div>
      <div class="info-item">
        <span class="info-label">电子邮箱：</span>
        <span class="info-value">{{ user.email }}</span>
      </div>
      <div class="info-item">
        <span class="info-label">安全问题：</span>
        <span class="info-value">{{ user.securityQuestion }}</span>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <button @click="showEditDialog" class="edit-btn">编辑信息</button>
    </div>

    <!-- 编辑信息弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑个人信息"
      width="90%"
      :before-close="handleCloseDialog"
    >
      <div class="edit-form">
        <div class="form-group">
          <label>用户名</label>
          <el-input v-model="editForm.username" :disabled="true" />
        </div>

        <div class="form-group">
          <label>昵称</label>
          <el-input v-model="editForm.nickname" />
        </div>

        <div class="form-group">
          <label>手机号</label>
          <el-input v-model="editForm.phone" />
        </div>

        <div class="form-group">
          <label>电子邮箱</label>
          <el-input v-model="editForm.email" />
        </div>

        <div class="form-group">
          <label>安全问题</label>
          <el-input v-model="editForm.securityQuestion" />
        </div>

        <div class="form-group">
          <label>新密码</label>
          <el-input
            v-model="editForm.newPassword"
            type="password"
            placeholder="留空则不修改"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveChanges" :loading="loading"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  data() {
    return {
      user: {
        userId: null,
        username: "",
        nickname: "",
        avatarUrl: "",
        phone: "",
        email: "",
        securityQuestion: "",
        securityAnswer: "",
        role: "",
      },
      editDialogVisible: false,
      editForm: {
        username: "",
        nickname: "",
        phone: "",
        email: "",
        securityQuestion: "",
        newPassword: "",
      },
      loading: false,
    };
  },
  created() {
    this.loadUserData();
  },
  methods: {
    async loadUserData() {
      try {
        this.loading = true;
        const userId = localStorage.getItem("userId");
        if (!userId) {
          console.error("用户未登录");
          return;
        }

        const response = await axios.post(
          `http://localhost:8081/user/get/${userId}`
        );
        if (response.data.code === 200) {
          this.user = response.data.data;
        } else {
          throw new Error(response.data.message || "获取用户信息失败");
        }
      } catch (error) {
        console.error("加载用户数据失败:", error);
        ElMessage.error("加载用户信息失败，请重试");
      } finally {
        this.loading = false;
      }
    },

    showEditDialog() {
      this.editForm = {
        username: this.user.username,
        nickname: this.user.nickname,
        phone: this.user.phone,
        email: this.user.email,
        securityQuestion: this.user.securityQuestion,
        newPassword: "",
      };
      this.editDialogVisible = true;
    },

    handleCloseDialog(done) {
      if (
        JSON.stringify(this.editForm) !==
        JSON.stringify({
          username: this.user.username,
          nickname: this.user.nickname,
          phone: this.user.phone,
          email: this.user.email,
          securityQuestion: this.user.securityQuestion,
          newPassword: "",
        })
      ) {
        ElMessageBox.confirm("确定放弃修改吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            done();
          })
          .catch(() => {});
      } else {
        done();
      }
    },

    async saveChanges() {
      try {
        this.loading = true;

        // 构建更新对象
        const updateData = {
          userId: this.user.userId,
          username: this.editForm.username,
          nickname: this.editForm.nickname,
          phone: this.editForm.phone,
          email: this.editForm.email,
          securityQuestion: this.editForm.securityQuestion,
          securityAnswer: this.user.securityAnswer,
        };

        // 如果有新密码，添加到更新对象
        if (this.editForm.newPassword) {
          updateData.password = this.editForm.newPassword;
        }

        // 发送JSON格式请求
        const response = await axios.post(
          "http://localhost:8081/user/update",
          updateData,
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        );
        console.log(response);
        if (response.data.code !== 200) {
          throw new Error(response.data.message || "更新用户信息失败");
        }

        ElMessage.success("个人信息更新成功");
        this.editDialogVisible = false;
        this.loadUserData();
      } catch (error) {
        console.error("更新用户信息失败:", error);
        ElMessage.error(error.message || "更新失败，请重试");
      } finally {
        this.loading = false;
      }
    },

    handleAvatarChange(event) {
      const file = event.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = (e) => {
        this.user.avatarUrl = e.target.result;
      };
      reader.readAsDataURL(file);
    },

    handleLogout() {
      ElMessageBox.confirm("确定要退出登录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 清空localStorage中的用户信息
          localStorage.removeItem("userId");
          localStorage.removeItem("user");
          // 跳转到登录页面
          this.$router.push("/front/login");
          ElMessage.success("已退出登录");
        })
        .catch(() => {});
    },
  },
};
</script>

<style scoped>
.user-profile-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
    Arial, sans-serif;
}

.profile-header {
  text-align: center;
  margin-bottom: 30px;
  position: relative;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 15px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #eee;
}

.edit-avatar-btn {
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 15px;
  padding: 3px 10px;
  font-size: 12px;
  cursor: pointer;
}

.logout-btn {
  position: absolute;
  top: 0;
  right: 0;
  background: #f5222d;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  font-size: 12px;
  cursor: pointer;
}

.username {
  margin: 0;
  color: #333;
}

.profile-info {
  margin-bottom: 30px;
}

.info-item {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.info-label {
  font-weight: bold;
  color: #666;
}

.info-value {
  color: #333;
}

.action-buttons {
  text-align: center;
}

button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.edit-btn {
  background-color: #1890ff;
  color: white;
}

.edit-form .form-group {
  margin-bottom: 15px;
}

.edit-form label {
  display: block;
  margin-bottom: 5px;
  color: #666;
  font-size: 14px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>